<template>
  <div class="carbon-platform d-flex flex-column min-vh-100">
    <!-- 加载动画 -->
    <div class="preloader-wrapper" v-if="isLoading">
      <div class="preloader"></div>
    </div>

    <!-- 导航栏 - 保持不变 -->
    <nav class="navbar sticky-top bg-white shadow-sm py-3">
      <div class="container">
        <div class="d-flex justify-content-between align-items-center w-100">
          <!-- 网站标志 -->
          <div class="navbar-logo">
            <span class="logo-icon">🌱</span>
            <span class="logo-text">绿碳平台</span>
          </div>

          <!-- 中间导航链接 - 桌面版 -->
          <ul class="navbar-nav list-unstyled d-flex flex-row gap-3 gap-lg-5 justify-content-center flex-wrap align-items-center mb-0 fw-bold flex-grow-1 mx-4">
            <li class="nav-item">
              <a href="/index" class="nav-link text-dark hover:text-primary transition-colors">首页</a>
            </li>
            <li class="nav-item">
              <a href="/shop" class="nav-link text-dark hover:text-primary transition-colors">碳积分市场</a>
            </li>
            <li class="nav-item">
              <a href="/blog" class="nav-link text-dark hover:text-primary transition-colors">博客</a>
            </li>
            <li class="nav-item">
              <a href="/contact" class="nav-link text-dark hover:text-primary transition-colors">联系我们</a>
            </li>
            <li class="nav-item">
              <a href="/about" class="nav-link text-dark hover:text-primary transition-colors">关于我们</a>
            </li>
            <li class="nav-item">
              <a href="/order" class="nav-link text-dark hover:text-primary transition-colors">我的订单</a>
            </li>
          </ul>

          <!-- 右侧功能区 -->
          <div class="d-flex align-items-center gap-4 gap-lg-5">
            <!-- 搜索按钮 -->
            <button class="btn p-2 text-dark hover:text-primary transition-colors" aria-label="搜索">
              <span class="fs-5">🔍</span>
            </button>

            <!-- 购物车 -->
            <a href="/cart" class="btn p-2 text-dark hover:text-primary transition-colors position-relative" aria-label="购物车">
              <span class="fs-5">🛒</span>
            </a>

            <!-- 用户菜单 -->
            <div class="dropdown">
              <button class="btn p-2 text-dark hover:text-primary transition-colors" type="button" data-bs-toggle="dropdown" aria-expanded="false" aria-label="用户菜单">
                <span class="fs-5">👤</span>
              </button>
              <ul class="dropdown-menu dropdown-menu-end">
                <li><a class="dropdown-item" href="/login">登录</a></li>
                <li><a class="dropdown-item" href="/register">注册</a></li>
                <li><a class="dropdown-item" href="/account">企业账户</a></li>
              </ul>
            </div>

            <!-- 移动端菜单按钮 -->
            <button class="btn d-lg-none p-2 text-dark" type="button" data-bs-toggle="offcanvas" data-bs-target="#mobileMenu" aria-label="菜单">
              <span class="fs-5">☰</span>
            </button>
          </div>
        </div>
      </div>
    </nav>

    <!-- 主内容区域 - 左侧图片+右侧表单布局 -->
    <main class="register-page flex-grow-1 bg-green-carbon">
      <div class="container-lg h-100">
        <!-- 外层容器：控制整体宽度和居中 -->
        <div class="row justify-content-center align-items-center h-100">
          <div class="col-12 col-xl-10 my-8"> <!-- 添加垂直外边距 -->
            <!-- 核心布局：左侧图片 + 右侧表单 -->
            <div class="row g-0 g-lg-8 align-items-center h-100">
              <!-- 左侧图片区域（仅桌面版显示） -->
              <div class="col-lg-6 d-none d-lg-flex h-100">
                <div class="register-image-wrapper rounded-lg overflow-hidden shadow-lg h-100 w-100">
                  <img
                      src="/images/img-login.jpg"
                      alt="绿碳平台环保理念展示"
                      class="register-image w-100 h-100 object-cover"
                  >
                </div>
              </div>

              <!-- 右侧表单区域 -->
              <div class="col-lg-6 h-100">
                <div class="card register-card shadow-lg border-0">
                  <div class="card-body p-6 p-lg-8 d-flex flex-column">
                    <!-- 表单标题 -->
                    <div class="text-center mb-6">
                      <h2 class="register-title">企业账户注册</h2>
                      <p class="text-muted">填写以下信息完成注册，成为绿碳平台企业用户</p>
                    </div>

                    <!-- 注册表单 -->
                    <form @submit.prevent="handleRegister" class="register-form flex-grow-1">
                      <!-- 企业基本信息 -->
                      <div class="mb-6">
                        <div class="row g-4">
                          <div class="col-md-6">
                            <label for="companyName" class="form-label required">企业名称</label>
                            <input type="text" id="companyName" name="companyName" class="form-control"
                                   v-model="registerForm.name"
                                   :class="{ 'is-invalid': errors.name }"
                                   placeholder="请输入企业全称" required>
                            <div class="invalid-feedback">{{ errors.name }}</div>
                          </div>
                          <div class="col-md-6">
                            <label for="creditCode" class="form-label required">统一社会信用代码</label>
                            <input type="text" id="creditCode" name="creditCode" class="form-control"
                                   v-model="registerForm.creditCode"
                                   :class="{ 'is-invalid': errors.creditCode }"
                                   placeholder="18位统一社会信用代码" required>
                            <div class="invalid-feedback">{{ errors.creditCode }}</div>
<!--                            <small class="text-muted d-block mt-1">用于企业身份唯一验证</small>-->
                          </div>
                        </div>
                      </div>

                      <!-- 账户安全信息 -->
                      <div class="mb-6 mt-3">
                        <div class="row g-4">
                          <div class="col-md-6">
                            <label for="password" class="form-label required">设置密码</label>
                            <input type="password" id="password" name="password" class="form-control"
                                   v-model="registerForm.password"
                                   :class="{ 'is-invalid': errors.password }"
                                   placeholder="请设置登录密码" required>
                            <div class="invalid-feedback">{{ errors.password }}</div>
                            <small class="text-muted d-block mt-1">密码长度至少6位，必须包含字母和数字</small>
                          </div>
                          <div class="col-md-6">
                            <label for="confirmPassword" class="form-label required">确认密码</label>
                            <input type="password" id="confirmPassword" name="confirmPassword" class="form-control"
                                   v-model="registerForm.confirmPassword"
                                   :class="{ 'is-invalid': errors.confirmPassword }"
                                   placeholder="请再次输入密码" required>
                            <div class="invalid-feedback">{{ errors.confirmPassword }}</div>
                          </div>
                        </div>
                      </div>

                      <!-- 协议同意 -->
                      <div class="mb-6 form-check mt-4">
                        <input type="checkbox" id="agreeTerms" name="agreeTerms" class="form-check-input"
                               v-model="registerForm.agreeTerms"
                               :class="{ 'is-invalid': errors.agreeTerms }"
                               required>
                        <label for="agreeTerms" class="form-check-label">
                          我已阅读并同意<a href="#" class="text-primary">《用户服务协议》</a>和<a href="#" class="text-primary">《隐私政策》</a>
                        </label>
                        <div class="invalid-feedback">{{ errors.agreeTerms }}</div>
                      </div>

                      <!-- 提交按钮 -->
                      <div class="d-grid gap-3 mt-auto">
                        <button type="submit" class="btn btn-primary btn-lg" :disabled="isSubmitting">
                          {{ isSubmitting ? '注册中...' : '完成注册' }}
                        </button>
                        <p class="text-center text-muted">
                          已有账号？<a href="/login" class="text-primary">立即登录</a>
                        </p>
                      </div>
                    </form>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </main>

    <!-- 页脚 - 固定在页面底部 -->
    <footer class="main-footer mt-auto">
      <div class="container">
        <div class="footer-bottom">
          <p class="copyright">© 2025 绿碳平台 版权所有 | 京ICP备12345678号</p>
        </div>
      </div>
    </footer>
  </div>
</template>

<script>
import { userApi } from '../api/index.js'

export default {
  name: 'Register',
  data() {
    return {
      isLoading: false,
      isSubmitting: false,
      registerForm: {
        name: '',
        creditCode: '',
        industry: '',
        scale: '',
        address: '',
        password: '',
        confirmPassword: '',
        agreeTerms: false
      },
      errors: {}
    };
  },
  methods: {
    validateForm() {
      const errors = {};
      const {
        name, creditCode, industry, password,
        confirmPassword, agreeTerms
      } = this.registerForm;

      // 企业信息验证
      if (!name) errors.name = '请输入企业名称';

      if (!creditCode) {
        errors.creditCode = '请输入统一社会信用代码';
      } else if (!/^[0-9A-HJ-NPQRTUWXY]{2}\d{6}[0-9A-HJ-NPQRTUWXY]{10}$/.test(creditCode)) {
        errors.creditCode = '请输入有效的18位统一社会信用代码';
      }

      // 密码验证
      if (!password) {
        errors.password = '请设置密码';
      } else if (password.length < 6) {
        errors.password = '密码长度至少6位';
      } else if (!password.match(/.*\d.*/) || !password.match(/.*[a-zA-Z].*/)) {
        errors.password = '密码必须包含字母和数字';
      }

      if (!confirmPassword) {
        errors.confirmPassword = '请再次输入密码';
      } else if (confirmPassword !== password) {
        errors.confirmPassword = '两次输入的密码不一致';
      }

      // 协议同意验证
      if (!agreeTerms) errors.agreeTerms = '请阅读并同意服务协议和隐私政策';

      this.errors = errors;
      return Object.keys(errors).length === 0;
    },
    async handleRegister() {
      if (!this.validateForm()) return;

      this.isSubmitting = true;
      try {
        // 准备注册数据
        const registerData = {
          username: this.registerForm.creditCode, // 使用统一社会信用代码作为用户名
          passwordHash: this.registerForm.password, // 后端期望的字段名
          phoneNumber: '', // 可选字段
          role: 'BUYER', // 使用正确的枚举值
          targetCredit: 0, // 默认目标碳积分
          userImage: '' // 默认头像
        };

        // 调用后端注册API
        const response = await userApi.register(registerData);
        
        if (response.data && response.data.code === '1') {
          // 注册成功，跳转到登录页
          this.$router.push({
            path: '/login',
            query: { message: '注册成功，请登录' }
          });
        } else {
          // 注册失败，显示错误信息
          const errorMessage = response.data?.message || '注册失败';
          if (errorMessage.includes('用户名') || errorMessage.includes('username')) {
            this.errors.creditCode = '该统一社会信用代码已被注册';
          } else {
            this.errors.creditCode = errorMessage;
          }
        }
      } catch (error) {
        console.error('注册失败:', error);
        if (error.response && error.response.data) {
          const errorMessage = error.response.data.message || '注册失败，请检查网络连接';
          if (errorMessage.includes('用户名') || errorMessage.includes('username')) {
            this.errors.creditCode = '该统一社会信用代码已被注册';
          } else {
            this.errors.creditCode = errorMessage;
          }
        } else {
          this.errors.creditCode = '注册失败，请稍后重试';
        }
      } finally {
        this.isSubmitting = false;
      }
    }
  }
};
</script>

<style scoped>
/* 基础样式 */
.navbar-logo {
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 1.5rem;
  font-weight: bold;
  color: #2e7d32; /* 绿色主色调 */
}

.register-page {
  padding: 2rem 0; /* 增加主内容区域的内边距 */
  display: flex;
  align-items: center;
}

.register-card {
  border-radius: 12px;
  background-color: white;
  max-width: 500px;
  width: 100%;
  margin: 0 auto;
  display: flex;
  flex-direction: column;
}

.register-title {
  font-size: 1.8rem;
  font-weight: 700;
  color: #2e7d32;
}

.form-label.required::after {
  content: '*';
  color: #dc3545;
  margin-left: 4px;
}

/* 表单元素样式 */
.form-control, .form-select {
  border-radius: 8px;
  padding: 0.75rem;
  border: 1px solid #ced4da;
  transition: all 0.3s ease;
  /* 兼容性修复 */
  -webkit-text-size-adjust: 100%;
  text-size-adjust: 100%;
  -ms-touch-action: manipulation;
  touch-action: manipulation;
}

.form-control:focus, .form-select:focus {
  border-color: #4caf50;
  box-shadow: 0 0 0 0.25rem rgba(76, 175, 80, 0.25);
  outline: none;
}


/* 按钮样式 */
.btn-primary {
  background-color: #2e7d32;
  border-color: #2e7d32;
  padding: 0.75rem;
  font-weight: 600;
  border-radius: 8px;
  transition: all 0.3s ease;
}

.btn-primary:hover, .btn-primary:focus {
  background-color: #1b5e20;
  border-color: #1b5e20;
  transform: translateY(-2px);
}

/* 图片区域样式 */
.register-image-wrapper {
  border-radius: 12px;
  height: 100%;
  min-height: 500px;
}

/* 页脚样式 - 固定在底部 */
.main-footer {
  background-color: #2E7D32;
  padding: 2rem 0;
  width: 100%;
}

.copyright {
  text-align: center;
  margin: 0;
  color: #fff;
}

/* 响应式调整 */
@media (max-width: 991.98px) {
  .register-image-wrapper {
    display: none;
  }

  .register-card {
    margin-top: 2rem;
    margin-bottom: 2rem;
  }

  .register-page {
    padding: 1rem 0;
  }
}

/* 动画效果 */
.transition-colors {
  transition: color 0.3s ease;
}

/* 加载动画 */
.preloader-wrapper {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(255, 255, 255, 0.8);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 9999;
}

.preloader {
  width: 50px;
  height: 50px;
  border: 5px solid #f3f3f3;
  border-top: 5px solid #2e7d32;
  border-radius: 50%;
  animation: spin 1s linear infinite;
}

@keyframes spin {
  0% {
    transform: rotate(0deg);
  }
  100% {
    transform: rotate(360deg);
  }
}
</style>